package org.jflame.devAide.plugin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import org.jflame.devAide.plugin.websocket.WebsocketTestController;
import org.jflame.devAide.util.Loger;
import org.jflame.devAide.util.ResourceUtils;

public final class PluginFactory {

    private static List<ToolPlugin> plugins = new ArrayList<>();

    static {
        loadPlugins();
    }

    public static List<ToolPlugin> getPlugins() {
        return plugins;
    }

    private static void loadPlugins() {
        // 先加载内部插件实现
        createInnerPlugins();
        // 再加载外部实现
        ServiceLoader<ToolPlugin> sloader = ServiceLoader.load(ToolPlugin.class);
        Iterator<ToolPlugin> it = sloader.iterator();
        while (it.hasNext()) {
            plugins.add(it.next());
        }

        Collections.sort(plugins);
        Loger.debug("load plugins qty:{}", plugins.size());
    }

    private static void createInnerPlugins() {

        PluginInfo pi_regex = new PluginInfo(ResourceUtils.getString("plugin.regex.name"),
                PluginFactory.class.getResource("regexTester.fxml"), "@SORT_ALPHA_ASC", 1);
        plugins.add(new InnerPlugin(pi_regex));
        pi_regex.setDesc("正则表达式测试,正则替换,常用正则表达式,正则语法");
        pi_regex.setFav(true);

        PluginInfo pi_format = new PluginInfo(ResourceUtils.getString("plugin.formatter.name"),
                PluginFactory.class.getResource("formatTool.fxml"), "@BARS", 2);
        plugins.add(new InnerPlugin(pi_format));
        pi_format.setDesc("代码格式化,支持:xml,json(可树形查看),sql,css");

        PluginInfo pi_barcode = new PluginInfo(ResourceUtils.getString("plugin.bc.name"),
                PluginFactory.class.getResource("qrcodeTool.fxml"), "@QRCODE", 3);
        pi_barcode.setDesc("生成各类型一维条码和二维码");
        plugins.add(new InnerPlugin(pi_barcode));

        PluginInfo pi_cron = new PluginInfo(ResourceUtils.getString("plugin.cron.name"),
                PluginFactory.class.getResource("cronTool.fxml"), "@CLOCK_ALT", 4);
        pi_cron.setDesc("可视化构建CRON表达式,反解析CRON");
        plugins.add(new InnerPlugin(pi_cron));

        PluginInfo pi_websocket = new PluginInfo(ResourceUtils.getString("plugin.websocket.name"),
                PluginFactory.class.getResource("websocketTester.fxml"), "@EXCHANGE", 5);
        plugins.add(new InnerPlugin(pi_websocket, new WebsocketTestController()));

    }

}
